﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo01.Repsotories
{
    /// <summary>
    ///  数据库操作公共库
    /// </summary>
    public static class DBHelper
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private static string connectionString = "SERVER=.;DATABASE=UCSTDB;UID=sa;PWD=123456";

        public static string ConnectionString 
        { 
            get { return connectionString; } 
        }

        /// <summary>
        /// 执行SELECT语句
        /// </summary>
        /// <param name="sqlText"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static SqlDataReader Query(string sqlText ,params SqlParameter[] parameters )
        {
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = sqlText;
            // 添加参数
            cmd.Parameters.Clear();
            if (null != parameters && parameters.Length > 0)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    cmd.Parameters.Add(parameter);

                }
            }

            SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            return reader;


        }


        /// <summary>
        /// 执行DML： insert/update/delete
        /// </summary>
        /// <param name="sqlText"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string sqlText , params SqlParameter[] parameters)
        {
            SqlConnection con = new SqlConnection(DBHelper.ConnectionString);

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = sqlText;
                cmd.Parameters.Clear();
                if(null != parameters && parameters.Length > 0)
                {
                    foreach(SqlParameter parameter in parameters)
                    {
                        cmd.Parameters.Add(parameter);
                    }
                }
                return cmd.ExecuteNonQuery();
               
            }
            finally
            {
                con.Close();
            }


        }
    }
}
